<template>
  <section>
    <search-bar more-display>
      <el-row :data="condition">
        <el-col :span="8">
          <el-form-item label="货物名称">
            <el-input style="width: 375px" v-model="condition.name"
                      placeholder="请输入货物品名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货物类型" prop="type">
            <el-select v-model="condition.type" placeholder="请选择货物类型">
              <el-option
                v-for="item in typeDict"
                :label="item.cnDictValname"
                :key="item.dictVal"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否启用">
            <el-select v-model="condition.status" placeholder="请选择启用状态">
              <el-option
                v-for="item in statusDict"
                :label="item.cnDictValname"
                :key="item.dictVal"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <el-col v-bind:span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handelBathDelete">批量删除</el-button>
      <el-button type="primary" @click="resetCondition" style="float: right">重置</el-button>
      <el-button type="primary" @click="getTableData" style="float: right">查询</el-button>
    </el-col>
    <!--列表-->
    <!--todo 自适应最大高度（系统统一列表最小和最大高度）-->
    <el-table :data="tableData" highlight-current-row border style="width: 100%;" min-height="450" max-height="600"
              v-loading="listLoading"
              @sort-change="sortChange"
              @selection-change="selsChange">
      <el-table-column type="selection" width="50" align="center">
      </el-table-column>
      <el-table-column prop="typeName" label="货物类型" width="180" align="center">
      </el-table-column>
      <el-table-column prop="name" label="货物品名" width="400" align="left">
      </el-table-column>
      <el-table-column prop="sorts" label="排序" width="120" align="center">
      </el-table-column>
      <el-table-column prop="status" label="状态(是否启用）" width="180" align="center" :formatter="dictFormatter">
      </el-table-column>
      <el-table-column prop="modifyDate" label="修改日期" width="250" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="getEditBYId(scope.$index,scope.row)">编辑</el-button>
          <el-button type="warning" v-if="scope.row.status === 111002001" size="small"
                     @click="statusModify(scope.$index,111002002,scope.row.id,'禁用')">禁用
          </el-button>
          <el-button type="success" v-if="scope.row.status === 111002002"
                     @click="statusModify(scope.$index,111002001,scope.row.id,'启用')">启用
          </el-button>
          <el-button type="danger" @click="handelDelete(scope.$index, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页信息工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--修改热门货物品名弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" size="tiny">
      <el-form :key="dialogKey" :model="dialogForm" ref="dialogForm" :rules="rules">
        <el-form-item label="货物类型" prop="type" :label-width="formLabelWidth">
          <el-select v-model="dialogForm.type" placeholder="请选择货物类型">
            <el-option
              v-for="item in typeDict"
              :label="item.cnDictValname"
              :key="item.dictVal"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货物品名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="dialogForm.name" style="width: 220px" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="货物排序" prop="sorts" :label-width="formLabelWidth">
          <el-input v-model.number="dialogForm.sorts" style="width: 220px" auto-complete="off" type="number"></el-input>
        </el-form-item>
        <!--后台接口默认禁用-->
        <el-form-item label="是否启用" prop="status" :label-width="formLabelWidth">
          <el-select disabled="true" v-model="itemStatus" placeholder="请选择启用状态">
            <el-option
              v-for="item in statusDict"
              :label="item.cnDictValname"
              :key="item.dictVal"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">提交</el-button>
        <!--<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { getItemNamesNew, saveItemName, modifyStatus, deleteItemName } from '../../api/system/ItemName';
import { getDictEntity } from '../../api/system/Dict';
import { getSelectObect } from '../../lib/util';

export default {
  data () {
    return {
      // 新增修改弹框随机key值
      dialogKey: 0,
      token: this.$store.state.token,
      // 列表页检索条件
      condition: {
        name: '',
        type: '',
        status: ''
      },
      // 加载货物类型、状态字典
      typeDict: [],
      statusDict: [],
      // 验证规则
      rules: {
        type: [
          {required: true, type: 'number', message: '请选择货物类型', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请输入热门货物品名'},
          {max: 15, message: '长度在 15字符内'}
        ],
        sorts: [
          {required: true, message: '请输入整数排序'},
          {type: 'integer', message: '请输入整数'}
        ]
        //                    status:[
        //                        {required: true, message: '请选是否启用', trigger: 'blur，change'}
        //                    ]
      },

      // 复选框选中数据（行）
      sels: [],
      // 列表数据
      tableData: [],

      // 数据加载中提示显示控制属性
      listLoading: false,
      submitLoading: false,

      // 分页排序设置
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'sorts',
      //                sortProp: null,
      sortOrder: 'descending',
      //                ascending 排序

      // 弹框数据及属性
      dialogTitle: '新增',
      // 新增修改类型，状态值
      itemType: null,
      itemStatus: null,
      dialogForm: {
        'description': null,
        'id': null,
        'name': null,
        'status': null,
        'type': this.itemType,
        'typeName': null,
        'sorts': this.itemStatus
      },
      dialogFormVisible: false,
      formLabelWidth: '180px'
      // searchConditionLabelWidth: '80px'

    };
  },
  methods: {
    // 表格字典值转换成字典名
    dictFormatter (row, column) {
      if (this.statusDict.length === 0) {
        return row.status;
      }
      for (let p in this.statusDict) {
        if (this.statusDict[p].dictVal === row.status) {
          return this.statusDict[p].cnDictValname;
        }
      }
      return '';
    },
    // 选择改变事件（包括全选/全不选、单选/单取消）传入的值为选中的复选框）
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.getTableData();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.getTableData();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 重置查询条件
    resetCondition () {
      for (let p in this.condition) {
        this.condition[p] = null;
      }
    },
    // 获取表格数据
    getTableData () {
      let str = [];
      if (this.condition.name !== '' && this.condition.name !== null) {
        str.push('LIKE_name=' + this.condition.name);
      }
      if (this.condition.type !== '' && this.condition.type !== null) {
        str.push('EQ_type=' + this.condition.type);
      }
      if (this.condition.status !== '' && this.condition.status !== null) {
        str.push('EQ_status=' + this.condition.status);
      }
      this.listLoading = true;
      getItemNamesNew({
        filters: str.join(';'),
        sort: 'createdDate,desc',
        page: this.currentPage - 1,
        size: this.pageSize
      }).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data;
          this.total = Number(res.headers['x-total-count']);
          this.listLoading = false;
        }
      });
    },

    // 获取类型字典数据
    getTypeDict () {
      let dictCode = 109004;
      getDictEntity({
        token: this.$store.state.token,
        page: 1,
        size: 20,
        filters: 'dictCode=' + dictCode,
        sorts: '+dictVal'
      }).then((res) => {
        this.typeDict = res.data.detailModelList;
      });
    },
    // 获取状态字典数据
    getStatusDict () {
      let dictCode = 111002;
      getDictEntity({
        token: this.$store.state.token,
        page: 1,
        size: 20,
        filters: 'dictCode=' + dictCode,
        sorts: '+dictVal'
      }).then((res) => {
        this.statusDict = res.data.detailModelList;
      });
    },

    // 清空弹出框表单
    resetForm () {
      this.itemType = null;
      this.itemStatus = null;
      for (let p in this.dialogForm) {
        this.dialogForm[p] = null;
      }
    },

    // 弹出添加窗体
    handleAdd () {
      this.dialogKey = Math.random() - 0.5;
      this.dialogTitle = '新增';
      this.resetForm();
      this.itemStatus = null;
      this.itemType = null;
      this.dialogFormVisible = true;
    },

    // 打开新增/编辑页
    getEditBYId (index, row) {
      if (row.status === 111002001) {
        this.$message.error('已启用的货物不能修改！');
        return;
      }
      this.dialogKey = Math.random() - 0.5;
      this.dialogTitle = '修改';
      this.resetForm();
      this.dialogFormVisible = true;
      this.itemStatus = row.status;
      this.itemType = row.type;
      this.dialogForm = Object.assign({}, row);
    },
    // 新增修改窗口取消按钮
    resetDialogForm () {
      this.dialogFormVisible = false;
      this.resetForm();
    },
    // 新增修改数据提交
    handleSubmit () {
      // 表单验证
      this.$refs['dialogForm'].validate((valid) => {
        console.log(this.dialogForm);
        if (valid) {
          this.submitLoading = true;
          this.dialogForm.typeName = getSelectObect(this.dialogForm.type, 'dictVal', this.typeDict).cnDictValname;
          saveItemName(this.dialogForm).then((res) => {
            this.submitLoading = false;
            console.log(this.dialogForm);
            if (res.status === 201) {
              this.dialogFormVisible = false;
              this.$message.success(this.dialogTitle + '成功！');
              this.getTableData();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          this.$message.error('数据有误');
          //                        console.log('error submit!!');
          return false;
        }
      });
    },
    handelBathDelete () {
      let ids = this.sels.map(o => o.id);
      this.$confirm('确认批量删除热门商品吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteItemName(ids.join(',')).then((res) => {
          if (res.status === 200) {
            this.$message.success('删除成功');
            this.currentPage = 1;
            this.getTableData();
          }
        });
      });
    },
    handelDelete (index, id) {
      this.$confirm('确认删除该热门货品吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        deleteItemName(id).then((res) => {
          this.listLoading = false;
          if (res.status === 200) {
            this.$message({
              message: '恭喜删除成功！',
              type: 'success'
            });
            this.currentPage = 1;
            this.getTableData();
          } else {
            this.$message({
              message: '删除失败！',
              type: 'error'
            });
          }
        });
      }).catch(() => {
      });
    },
    // 状态变更
    statusModify (index, status, id, btnName) {
      this.$confirm('确认 ' + btnName + ' 该热门货品吗？', '提示', {
        type: 'info'
      }).then(() => {
        this.listLoading = true;
        modifyStatus(id, status).then((res) => {
          this.listLoading = false;
          if (res.status === 200) {
            this.$message({
              message: btnName + '成功！',
              type: 'success'
            });
            this.tableData[index].status = status;// 修改本地数据
          } else {
            this.$message({
              message: btnName + '失败！',
              type: 'error'
            });
          }
        });
      });
    }
  },
  // 初始化数据
  mounted () {
    this.getTableData();
    this.getTypeDict();
    this.getStatusDict();
  }
};
</script>

<style lang="less" scoped>
  .el-row {
    margin-bottom: 20px;
  }

  .active {
    display: none
  }
</style>
